import { Model } from 'mongoose';
import { ITaskSession, ISubTask } from '../models/types';

export class TaskSessionRepository {
  private model: Model<ITaskSession>;

  constructor(model: Model<ITaskSession>) {
    this.model = model;
  }

  // 创建新会话
  async create(sessionData: Partial<ITaskSession>): Promise<ITaskSession> {
    const newSession = new this.model(sessionData);
    return newSession.save();
  }

  // 根据ID查找会话
  async findById(sessionId: string): Promise<ITaskSession | null> {
    return this.model.findOne({ sessionId }).lean().exec();
  }

  // 更新会话状态和元数据
  async updateStatus(sessionId: string, status: ITaskSession['status'], userId: string): Promise<ITaskSession | null> {
    return this.model.findOneAndUpdate(
      { sessionId },
      {
        $set: {
          status,
          'metadata.lastModifiedBy': userId,
        },
      },
      { new: true } // 返回更新后的文档
    ).exec();
  }

  // 增加消息计数（原子操作）
  async incrementMessageCount(sessionId: string, lastMessageAt: Date): Promise<void> {
    await this.model.updateOne(
      { sessionId },
      {
        $inc: { messageCount: 1 },
        $set: { lastMessageAt },
      }
    ).exec();
  }

  // 查找活跃且高优的会话
  async findActiveHighPrioritySessions(userId: string): Promise<ITaskSession[]> {
    return this.model.find({
      userId,
      status: 'active',
      priority: { $in: ['high', 'urgent'] },
    })
    .sort({ createdAt: -1 })
    .limit(50)
    .lean().exec();
  }

  // ==================== 子任务相关方法 ====================

  // 添加子任务
  async addSubTask(sessionId: string, subTaskData: Omit<ISubTask, 'subTaskId' | 'createdAt' | 'updatedAt'>): Promise<ITaskSession | null> {
    const subTaskId = `subtask_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const newSubTask: ISubTask = {
      ...subTaskData,
      subTaskId,
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    const session = await this.model.findOneAndUpdate(
      { sessionId },
      {
        $push: { subTasks: newSubTask },
        $inc: { 'metadata.subTaskStats.total': 1, 'metadata.subTaskStats.pending': 1 },
      },
      { new: true }
    ).exec();

    // 重新计算整体进度
    if (session) {
      await this.recalculateProgress(sessionId);
    }

    return session;
  }

  // 更新子任务状态
  async updateSubTaskStatus(
    sessionId: string,
    subTaskId: string,
    status: ISubTask['status'],
    progress?: number
  ): Promise<ITaskSession | null> {
    const updateData: any = {
      'subTasks.$.status': status,
      'subTasks.$.updatedAt': new Date(),
    };

    if (progress !== undefined) {
      updateData['subTasks.$.progress'] = progress;
    }

    if (status === 'completed') {
      updateData['subTasks.$.completedAt'] = new Date();
      updateData['subTasks.$.progress'] = 100;
    }

    const session = await this.model.findOneAndUpdate(
      { sessionId, 'subTasks.subTaskId': subTaskId },
      { $set: updateData },
      { new: true }
    ).exec();

    // 更新统计信息和整体进度
    if (session) {
      await this.updateSubTaskStats(sessionId);
      await this.recalculateProgress(sessionId);
    }

    return session;
  }

  // 删除子任务
  async removeSubTask(sessionId: string, subTaskId: string): Promise<ITaskSession | null> {
    const session = await this.model.findOneAndUpdate(
      { sessionId },
      { $pull: { subTasks: { subTaskId } } },
      { new: true }
    ).exec();

    if (session) {
      await this.updateSubTaskStats(sessionId);
      await this.recalculateProgress(sessionId);
    }

    return session;
  }

  // 重新计算整体进度
  private async recalculateProgress(sessionId: string): Promise<void> {
    const session = await this.model.findOne({ sessionId }).lean().exec();
    if (!session || session.subTasks.length === 0) {
      await this.model.updateOne(
        { sessionId },
        { $set: { overallProgress: 0 } }
      ).exec();
      return;
    }

    const totalProgress = session.subTasks.reduce((sum, task) => sum + task.progress, 0);
    const overallProgress = Math.round(totalProgress / session.subTasks.length);

    await this.model.updateOne(
      { sessionId },
      { $set: { overallProgress } }
    ).exec();
  }

  // 更新子任务统计信息
  private async updateSubTaskStats(sessionId: string): Promise<void> {
    const session = await this.model.findOne({ sessionId }).lean().exec();
    if (!session) return;

    const stats = {
      total: session.subTasks.length,
      completed: session.subTasks.filter(t => t.status === 'completed').length,
      inProgress: session.subTasks.filter(t => t.status === 'in_progress').length,
      pending: session.subTasks.filter(t => t.status === 'pending').length,
      cancelled: session.subTasks.filter(t => t.status === 'cancelled').length,
    };

    await this.model.updateOne(
      { sessionId },
      { $set: { 'metadata.subTaskStats': stats } }
    ).exec();
  }

  // 获取子任务依赖关系
  async getSubTaskDependencies(sessionId: string, subTaskId: string): Promise<ISubTask[]> {
    const session = await this.model.findOne({ sessionId }).lean().exec();
    if (!session) return [];

    const subTask = session.subTasks.find(t => t.subTaskId === subTaskId);
    if (!subTask || !subTask.dependencies.length) return [];

    return session.subTasks.filter(t => subTask.dependencies.includes(t.subTaskId));
  }

  // 检查子任务是否可以开始（依赖项已完成）
  async canStartSubTask(sessionId: string, subTaskId: string): Promise<boolean> {
    const dependencies = await this.getSubTaskDependencies(sessionId, subTaskId);
    return dependencies.every(dep => dep.status === 'completed');
  }
}
